package com.ccdt.tv.smartrecommend.utils;

import android.app.Service;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.os.IBinder;
import android.text.TextUtils;
import android.util.Log;

import com.google.gson.Gson;

import java.util.List;

import cn.ljwl.bn.dvb.service.IDVBInfoService;

/**
 * Created by sheng on 2018/9/13.
 * 智能推荐服务管理类
 */

public class DVBServiceManager {

    private static final String SERVICE_ACTION = "cn.ljwl.bn.dvb.service.DVBInfoService";

    private static final String TAG = "DVBServiceManager";
    Context mContext = null;
    private IDVBInfoService mService = null;
    private static DVBServiceManager mManager = null;
    private Gson mGson;

    public static DVBServiceManager getInstance(Context context) {
        if (null == mManager) {
            synchronized (DVBServiceManager.class) {
                Log.w(TAG, "getInstance: make new manager");
                mManager = new DVBServiceManager(context);
            }
        }
        return mManager;
    }

    public DVBServiceManager(Context mContext) {
        this.mGson = new Gson();
        this.mContext = mContext;
    }

    public IDVBInfoService getDVBServie() {
        if (null == mService) {
            Log.d(TAG, "getDVBServie: ");
            this.bindService();
        }
        return mService;
    }

    public boolean bindService() {
        Log.w(TAG, "bindService: "+mService );
        if (null == mService) {
            try{
                Log.d(TAG, "connectService: ");
                final Intent eintent = new Intent(
                        createExplicitFromImplicitIntent(mContext, new Intent(SERVICE_ACTION)));
                mContext.bindService(eintent, scc, Service.BIND_AUTO_CREATE);
            }catch (Exception e){
                Log.w(TAG, "bindService: bind dvb service error!" );
                e.printStackTrace();
            }

        }
        return true;
    }

    private void reBind() {
        unbindDVBService();
        bindService();
    }
    /**
     * 隐式意图显式调用
     *
     * @param context
     * @param implicitIntent
     * @return
     */
    public static Intent createExplicitFromImplicitIntent(Context context, Intent implicitIntent) {
        // Retrieve all services that can match the given intent
        PackageManager pm = context.getPackageManager();
        List<ResolveInfo> resolveInfo = pm.queryIntentServices(implicitIntent, 0);

        // Make sure only one match was found
        if (resolveInfo == null || resolveInfo.size() != 1) {
            return null;
        }

        // Get component info and create ComponentName
        ResolveInfo serviceInfo = resolveInfo.get(0);
        String packageName = serviceInfo.serviceInfo.packageName;
        String className = serviceInfo.serviceInfo.name;
        ComponentName component = new ComponentName(packageName, className);

        // Create a new intent. Use the old one for extras and such reuse
        Intent explicitIntent = new Intent(implicitIntent);

        // Set the component to be explicit
        explicitIntent.setComponent(component);

        return explicitIntent;
    }

    ServiceConnection scc = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            Log.d(TAG, "onServiceConnected: "+name.getPackageName()+"----"+name.getPackageName());
            mService = IDVBInfoService.Stub.asInterface(service);
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            Log.d(TAG, "onServiceDisconnected: ");
            mService = null;
        }
    };

    /**
     * 取消绑定智能推荐服务
     */
    public void unbindDVBService() {
        Log.i(TAG, "unbindDVBService, mService = " + mService);
        try{
            if (null != mService) {
                mContext.unbindService(scc);
                mService = null;
            }
        }catch (Exception e){
            Log.e(TAG, "unbindDVBService: unbind dvb service error!" );
        }
    }

    /*  {
        "retCode":"1代表成功，0代表失败",
        "nid":"100",
        "tid":"0001",
        "sid":"0001",
        "desc":"描述信息"
    }*/

    public class LiveInfo{
        private String retCode;
        private String nid;
        private String tid;
        private String sid;
        private String desc;

        public String getRetCode() {
            return retCode;
        }

        public void setRetCode(String retCode) {
            this.retCode = retCode;
        }

        public String getNid() {
            return nid;
        }

        public void setNid(String nid) {
            this.nid = nid;
        }

        public String getTid() {
            return tid;
        }

        public void setTid(String tid) {
            this.tid = tid;
        }

        public String getSid() {
            return sid;
        }

        public void setSid(String sid) {
            this.sid = sid;
        }

        public String getDesc() {
            return desc;
        }

        public void setDesc(String desc) {
            this.desc = desc;
        }
    }

    /*{
        "retCode":"1代表成功，0代表失败",
        "pName":"夏洛特烦恼",
        "desc":"描述信息"
    }*/
    public class ProgramInfo{
        private String retCode;
        private String pName;
        private String desc;

        public String getRetCode() {
            return retCode;
        }

        public void setRetCode(String retCode) {
            this.retCode = retCode;
        }

        public String getpName() {
            return pName;
        }

        public void setpName(String pName) {
            this.pName = pName;
        }

        public String getDesc() {
            return desc;
        }

        public void setDesc(String desc) {
            this.desc = desc;
        }
    }

    /**
     * 获取直播信息
     * @return
     */
    public LiveInfo getLiveInfo(){
        String liveJson="";
        try {
            liveJson = mService.getChannelInfo();
            Log.w(TAG, "getLiveInfo: liveJson："+liveJson );
        } catch (Exception e) {
            Log.e(TAG, "getLiveInfo: getChannelInfo error" );
            e.printStackTrace();
            unbindDVBService();
            bindService();
        }
        if (TextUtils.isEmpty(liveJson)){
            Log.e(TAG, "getLiveInfo: liveJson is null " );
            return null;
        }else {
            return mGson.fromJson(liveJson, LiveInfo.class);
        }
    }

    /**
     * 获取节目名称
     * @return
     */
    public String getProgName(){
        String programJson="";
        try {
            programJson = mService.getProgramName();
            Log.w(TAG, "getProgName: programJson："+programJson );
        } catch (Exception e) {
            Log.e(TAG, "getProgName: getProgramName error" );
            e.printStackTrace();
            unbindDVBService();
            bindService();
        }
        if (TextUtils.isEmpty(programJson)){
            Log.e(TAG, "getProgName: programJson is null " );
            return null;
        }else {
            return mGson.fromJson(programJson, ProgramInfo.class).getpName();
        }
    }
}
